<template>
  <div class="invoice-management">
    <!-- 功能卡片区域 -->
    <el-row :gutter="20" class="feature-cards">
      <el-col :span="6">
        <el-card shadow="hover" @click="handleNavigate('template')">
          <template #header>
            <div class="card-header">
              <el-icon><Document /></el-icon>
              <span>发票模板管理</span>
            </div>
          </template>
          <div class="card-content">
            <p>管理发票模板，设置发票抬头、税号等信息</p>
            <el-button type="primary" link>立即管理</el-button>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" @click="handleNavigate('auto')">
          <template #header>
            <div class="card-header">
              <el-icon><Timer /></el-icon>
              <span>自动开票设置</span>
            </div>
          </template>
          <div class="card-content">
            <p>配置自动开票规则，设置开票条件和触发方式</p>
            <el-button type="primary" link>立即设置</el-button>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" @click="handleNavigate('reconciliation')">
          <template #header>
            <div class="card-header">
              <el-icon><Money /></el-icon>
              <span>发票对账</span>
            </div>
          </template>
          <div class="card-content">
            <p>查看发票开具记录，进行对账和核对</p>
            <el-button type="primary" link>立即对账</el-button>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" @click="handleNavigate('statistics')">
          <template #header>
            <div class="card-header">
              <el-icon><TrendCharts /></el-icon>
              <span>统计分析</span>
            </div>
          </template>
          <div class="card-content">
            <p>查看发票开具统计，分析开票趋势</p>
            <el-button type="primary" link>查看统计</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最近发票记录 -->
    <el-card class="recent-invoices">
      <template #header>
        <div class="card-header">
          <span>最近发票记录</span>
          <div class="header-actions">
            <el-button type="primary" @click="handlePrint">批量打印</el-button>
            <el-button type="success" @click="handleExport">导出记录</el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="invoiceList"
        border
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="invoiceNo" label="发票号码" min-width="180" show-overflow-tooltip />
        <el-table-column prop="orderNo" label="订单编号" min-width="180" show-overflow-tooltip />
        <el-table-column prop="customerName" label="客户名称" width="120" />
        <el-table-column prop="amount" label="开票金额" width="120">
          <template #default="{ row }">
            ¥{{ row.amount?.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="type" label="发票类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.type === 'special' ? 'success' : 'info'">
              {{ row.type === 'special' ? '增值税专用发票' : '增值税普通发票' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getInvoiceStatusTag(row.status)">
              {{ getInvoiceStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="开具时间" min-width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">查看</el-button>
            <el-button 
              v-if="row.status === 'pending'"
              type="success" 
              link 
              @click="handlePrintSingle(row)"
            >
              打印
            </el-button>
            <el-button 
              v-if="row.status === 'pending'"
              type="warning" 
              link 
              @click="handleCancel(row)"
            >
              作废
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 发票详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="发票详情"
      width="700px"
    >
      <div class="invoice-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="发票号码">{{ currentInvoice.invoiceNo }}</el-descriptions-item>
          <el-descriptions-item label="发票代码">{{ currentInvoice.invoiceCode }}</el-descriptions-item>
          <el-descriptions-item label="订单编号">{{ currentInvoice.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="发票类型">
            <el-tag :type="currentInvoice.type === 'special' ? 'success' : 'info'">
              {{ currentInvoice.type === 'special' ? '增值税专用发票' : '增值税普通发票' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="客户名称">{{ currentInvoice.customerName }}</el-descriptions-item>
          <el-descriptions-item label="税号">{{ currentInvoice.taxNumber }}</el-descriptions-item>
          <el-descriptions-item label="开票金额">¥{{ currentInvoice.amount?.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="税额">¥{{ currentInvoice.taxAmount?.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="价税合计">¥{{ currentInvoice.totalAmount?.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="开票状态">
            <el-tag :type="getInvoiceStatusTag(currentInvoice.status)">
              {{ getInvoiceStatusLabel(currentInvoice.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="开具时间">{{ currentInvoice.createTime }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ currentInvoice.remark || '无' }}</el-descriptions-item>
        </el-descriptions>

        <!-- 发票明细 -->
        <div class="invoice-items">
          <h3>发票明细</h3>
          <el-table :data="currentInvoice.items" border>
            <el-table-column prop="name" label="商品名称" min-width="200" />
            <el-table-column prop="spec" label="规格型号" width="120" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="quantity" label="数量" width="100" />
            <el-table-column prop="price" label="单价" width="120">
              <template #default="{ row }">
                ¥{{ row.price?.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="金额" width="120">
              <template #default="{ row }">
                ¥{{ row.amount?.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="taxRate" label="税率" width="100">
              <template #default="{ row }">
                {{ row.taxRate }}%
              </template>
            </el-table-column>
            <el-table-column prop="taxAmount" label="税额" width="120">
              <template #default="{ row }">
                ¥{{ row.taxAmount?.toFixed(2) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button 
            v-if="currentInvoice.status === 'pending'"
            type="primary" 
            @click="handlePrintSingle(currentInvoice)"
          >
            打印发票
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 作废发票对话框 -->
    <el-dialog
      v-model="cancelDialogVisible"
      title="作废发票"
      width="500px"
    >
      <el-form
        ref="cancelFormRef"
        :model="cancelForm"
        :rules="cancelRules"
        label-width="100px"
      >
        <el-form-item label="作废原因" prop="reason">
          <el-input
            v-model="cancelForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入作废原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCancelSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, Timer, Money, TrendCharts } from '@element-plus/icons-vue'
import {
  getMerchantInvoiceList,
  getMerchantInvoiceDetail,
  cancelMerchantInvoice,
  printMerchantInvoice,
  exportMerchantInvoices
} from '@/api/merchant'

const router = useRouter()

// 发票列表数据
const loading = ref(false)
const invoiceList = ref([])

// 分页信息
const page = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 发票详情对话框
const detailDialogVisible = ref(false)
const currentInvoice = ref({})

// 作废发票对话框
const cancelDialogVisible = ref(false)
const cancelFormRef = ref(null)
const cancelForm = reactive({
  id: '',
  reason: ''
})

// 作废表单验证规则
const cancelRules = {
  reason: [
    { required: true, message: '请输入作废原因', trigger: 'blur' },
    { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
  ]
}

// 获取发票列表
const getInvoiceList = async () => {
  loading.value = true
  try {
    const { data } = await getMerchantInvoiceList({
      page: page.current,
      size: page.size
    })
    invoiceList.value = data.list
    page.total = data.total
  } catch (error) {
    console.error('获取发票列表失败:', error)
    ElMessage.error('获取发票列表失败')
  } finally {
    loading.value = false
  }
}

// 页面导航
const handleNavigate = (type) => {
  router.push(`/merchant/invoice/${type}`)
}

// 查看发票详情
const handleView = async (row) => {
  try {
    const { data } = await getMerchantInvoiceDetail(row.id)
    currentInvoice.value = data
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取发票详情失败:', error)
  }
}

// 打印单个发票
const handlePrintSingle = async (row) => {
  try {
    await printMerchantInvoice(row.id)
    ElMessage.success('打印成功')
  } catch (error) {
    console.error('打印发票失败:', error)
  }
}

// 批量打印
const handlePrint = async () => {
  const selection = invoiceList.value.filter(item => item.status === 'pending')
  if (selection.length === 0) {
    ElMessage.warning('请选择待打印的发票')
    return
  }
  
  try {
    await printMerchantInvoice(selection.map(item => item.id))
    ElMessage.success('批量打印成功')
  } catch (error) {
    console.error('批量打印失败:', error)
  }
}

// 导出记录
const handleExport = async () => {
  try {
    await exportMerchantInvoices()
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出发票记录失败:', error)
  }
}

// 作废发票
const handleCancel = (row) => {
  currentInvoice.value = row
  cancelForm.id = row.id
  cancelForm.reason = ''
  cancelDialogVisible.value = true
}

// 提交作废
const handleCancelSubmit = async () => {
  if (!cancelFormRef.value) return
  
  try {
    await cancelFormRef.value.validate()
    await cancelMerchantInvoice(cancelForm)
    ElMessage.success('发票已作废')
    cancelDialogVisible.value = false
    getInvoiceList()
  } catch (error) {
    console.error('作废发票失败:', error)
  }
}

// 获取发票状态标签类型
const getInvoiceStatusTag = (status) => {
  const statusMap = {
    pending: 'warning',
    printed: 'success',
    cancelled: 'danger'
  }
  return statusMap[status] || ''
}

// 获取发票状态标签文本
const getInvoiceStatusLabel = (status) => {
  const statusMap = {
    pending: '待打印',
    printed: '已打印',
    cancelled: '已作废'
  }
  return statusMap[status] || status
}

// 分页大小变化
const handleSizeChange = (val) => {
  page.size = val
  getInvoiceList()
}

// 页码变化
const handleCurrentChange = (val) => {
  page.current = val
  getInvoiceList()
}

onMounted(() => {
  getInvoiceList()
})
</script>

<style lang="scss" scoped>
.invoice-management {
  padding: 20px;

  .feature-cards {
    margin-bottom: 20px;

    .el-card {
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-5px);
      }

      .card-header {
        display: flex;
        align-items: center;
        gap: 10px;
        font-size: 16px;
        font-weight: 500;

        .el-icon {
          font-size: 20px;
        }
      }

      .card-content {
        p {
          margin: 10px 0;
          color: #666;
          font-size: 14px;
        }
      }
    }
  }

  .recent-invoices {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-actions {
        display: flex;
        gap: 10px;
      }
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .invoice-detail {
    .invoice-items {
      margin-top: 20px;

      h3 {
        margin-bottom: 15px;
        font-size: 16px;
        font-weight: 500;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 